﻿using System.IO;
using System.Linq;
using Microsoft.Practices.SharePoint.Common;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;
using SPContrib.App.Settings;
using SPContrib.Linq;

namespace SPContrib.Extensions
{
    /// <summary>
    /// Extension methods for the PublishingWeb class
    /// </summary>
    public static class PublishingWebExtensions
    {
        /// <summary>
        /// Retrieves the collection of settings for the PublishingWeb
        /// </summary>
        public static ISettingCollection Settings(this PublishingWeb instance)
        {
            return instance.Web.Settings();
        }

        /// <summary>
        /// Changes the masterpage on the publishing web instance
        /// </summary>
        /// <param name="masterpage">the SPFile that represents the masterpage</param>
        public static void AlterSiteMasterPage(this PublishingWeb instance, SPFile masterpage)
        {
            Validation.ArgumentNotNull(masterpage, "masterpage");

            instance.Web.EnsureUnsafeContext(ctx =>
                {
                    ctx.CustomMasterUrl = masterpage.ServerRelativeUrl;
                    ctx.Update();
                });

        }


        /// <summary>
        /// Tries to locate a publishing page by its name
        /// </summary>
        /// <param name="name">the name of the page to find</param>
        /// <param name="value">the PublishingPage instance to return if it is found</param>
        public static bool TryLocatePublishingPage(this PublishingWeb instance, string name, out PublishingPage value)
        {
            name = Path.GetFileNameWithoutExtension(name);                       

            string caml = @"
<Where>
    <Contains>
        <FieldRef Name='FileLeafRef' />
        <Value Type='File'>{0}</Value>
    </Contains>
</Where>".Trim();

            value = instance.GetPublishingPages(new SPQuery
            {
                RowLimit = 1,
                ViewAttributes = "Scope='Recursive'", // search subfolders
                Query = string.Format(caml, name)
            }).FirstOrDefault();

            return value != null;

        }

        /// <summary>
        /// Tries to locate a page layout by its name
        /// </summary>
        /// <param name="layout">the name of the page layout</param>
        /// <param name="value">the PageLayout instance to return if it is found</param>
        public static bool TryLocatePageLayout(this PublishingWeb instance, string layout, out PageLayout value)
        {
            value = default(PageLayout);
            SPList masterpages = instance.MasterPagesAndPageLayoutsLibrary();

            layout = Path.GetFileNameWithoutExtension(layout);

            string caml = @"
<Where>
    <Contains>
        <FieldRef Name='FileLeafRef' />
        <Value Type='File'>{0}</Value>
    </Contains>
</Where>".Trim();

            var result = masterpages.GetItems(new SPQuery
            {
                RowLimit = 1,
                Query = string.Format(caml, layout)
            });

            if (result.Count == 1)
            {
                value = instance.PublishingSite().PageLayouts[result[0].UniqueId];
            }

            return value != null;
        }

        /// <summary>
        /// Gets the PublishingSite that the PublishingWeb belongs to
        /// </summary>
        public static PublishingSite PublishingSite(this PublishingWeb instance)
        {
            return new PublishingSite(instance.Web.Site);
        }

        /// <summary>
        /// Gets a reference to the library that holds the masterpages and page layouts {_catalalogs\masterpage}
        /// </summary>
        public static SPList MasterPagesAndPageLayoutsLibrary(this PublishingWeb instance)
        {
            return instance.Web.MasterPagesAndPageLayoutsLibrary();
        }
    }
}
